import router from '@/router';
import { message } from '@/utils/restMessage.js';
import axios from 'axios';
// import { getCurrentInstance } from 'vue';
// const { proxy } = getCurrentInstance();
//  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// import { useRoute, useRouter } from "vue-router";
// const route = useRoute();
// const router = useRouter();
const myAxios = axios.create({
    baseURL: 'http://localhost:8080/api',
  //   timeout: 10000
})
  //解决跨域问题
myAxios.defaults.withCredentials = true;
//拦截器
myAxios.interceptors.request.use(config => {
    // 在发送请求之前做某事
    const token = localStorage.getItem('token') || ''; // 从本地存储获取token

      config.headers.Authorization = `${token}`;
    return config;
    // if(request.data)
  }, error => {
    // 对请求错误做些什么 
    return Promise.reject(error);
    // console.log(error)
  });

    //添加响应拦截器
    myAxios.interceptors.response.use(response => {
      console.log('我收到你的响应啦', response)
      console.log('status'+response.status)
      // 未登录则跳转到登录页
      // if(response.status==401){
      //   router.push('/')
      // }
      return response;
  
    }, error=> {
    //响应错误时做点什么
    if(error.response.status==401){
      // localStorage.clear()
      // ElMessage({
      //   showClose: true,
      //   message: '登录过期，请重新登录',
      //   type: 'error',
      //   })
      
      // proxy.$msg.error("登录过期，请重新登录")
      message.error("登录过期，请重新登录")
      localStorage.removeItem('token')
      localStorage.removeItem('userId')
      router.push('/')
    }

    return Promise.reject(error);
    });
export default myAxios;